import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/19 17:27
 * @Description: a. 一个生产者，多个消费者；
 * b. 每一个消费者都有自己的消息队列；
 * c. 生产者没有把消息发送到队列，而是发送到交换器exchange上；
 * d. 每个队列都需要绑定到交换机上；
 * e. 生产者生产的消息先经过交换机然后到达队列，一个消息可以被多个消费者消费
 */
public class ProviderPublish {

    private static final String PUBLISH_SUBSCRIBE_EXCHANGE_NAME = "publish_subscribe_exchange_fanout";

    //类型：分发
    private static final String PUBLISH_SUBSCRIBE_EXCHANGE_TYPE = "fanout";

    public static void main(String[] args) {
        //获取MQ连接
        Connection connection = MQConnecitonUtils.getConnection();
        //从连接中获取Channel通道对象
        Channel channel = null;

        try {
            //创建通道
            channel = connection.createChannel();

            channel.exchangeDeclare(PUBLISH_SUBSCRIBE_EXCHANGE_NAME, PUBLISH_SUBSCRIBE_EXCHANGE_TYPE, false, false, null);

            String msg = "hello,world!!";

            channel.basicPublish(PUBLISH_SUBSCRIBE_EXCHANGE_NAME, "", null, msg.getBytes("UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != channel) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != connection) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
